package com.jh.paymentchannel.service;

import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.DateUtil;
import cn.jh.common.utils.TokenUtil;
import com.jh.paymentchannel.business.RealnameAuthBusiness;
import com.jh.paymentchannel.pojo.RealNameAuth;
import com.jh.paymentchannel.util.Util;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@EnableAutoConfiguration
public class RealnameAuthService {


	private static final Logger LOG = LoggerFactory.getLogger(RealnameAuthService.class);

	@Autowired
	private RealnameAuthBusiness realnameAuthBusiness;

	@Autowired
	Util util;


	@Value("${jh.keyPlan}")
	private String keyPlan;
	/**
	 * 实名认证*小磊
	 *
	 * @param request
	 * @param sbrandId
	 * @param realname
	 * @param idcard
	 * @param phone
	 * @param token
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/realnames/auth/{token}")
	public @ResponseBody
	Object realnameAuths(HttpServletRequest request,
						 @RequestParam(value = "brandId", required = false, defaultValue = "-1") String sbrandId,
						 @RequestParam(value = "realname") String realname,
						 @RequestParam(value = "idcard") String idcard,
						 @RequestParam(value = "phone") String phone,
						 @PathVariable("token") String token) {

		Map<String, Object> map = new HashMap<>();
		long userId;
		try {
			userId = TokenUtil.getUserId(token);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}
		String birthDate;
		try {
			birthDate = idcard.substring(6, 10);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "您的身份证号有误,请重新输入!");
			return map;
		}
		int birthYear = Integer.valueOf(birthDate);
		int nowYear = Integer.valueOf(DateUtil.getDateStringConvert(new String(), new Date(), "yyyy"));
		if (nowYear - birthYear < 18 || nowYear - birthYear > 60) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "很抱歉,仅对年龄18岁~60岁用户进行实名认证!");
			return map;
		}

		realname = realname.trim();
		idcard = idcard.trim();
		RealNameAuth realNameAuth = realnameAuthBusiness.findRealNamesAuthByUserId(userId);
		if (realNameAuth != null && realNameAuth.getUserId() != userId) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "你的证件号已在其他账户认证");
			return map;
		}

		realNameAuth = realnameAuthBusiness.findRealNamesAuthByUsserId(userId);
		if (realNameAuth != null && realNameAuth.getAuthTime() != null) {
			long starttime = realNameAuth.getAuthTime().getTime();
			long endtime = System.currentTimeMillis();
			starttime = starttime + 60 * 10 * 1000;
			if (starttime > endtime) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "操作过于频繁，请10分钟后再试!");
				return map;
			}
		}

		realNameAuth = realnameAuthBusiness.findRealNamesByall(userId, idcard, realname);
		if (realNameAuth != null && "1".equals(realNameAuth.getResult())) {
			MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			RestTemplate restTemplate = new RestTemplate();
			URI url = util.getServiceUrl("user", "error url request!");
			String uri = url.toString() + "/v1.0/users/updatestatus/status";
			requestEntity.add("brandId", sbrandId);
			requestEntity.add("phone", phone);
			requestEntity.add("status", "1");
			String result = restTemplate.postForObject(uri, requestEntity, String.class);
			JSONObject jsonObject = JSONObject.fromObject(result);
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "接口返回成功");
			return map;
		}
   /*     if (realNameAuth == null || "".equals(realNameAuth.getResult())) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "接口返回失败");
            return map;
        }*/

		/**
		 * 根据userId去取brandId
		 */
		long brandid;
		try {
			brandid = TokenUtil.getBrandid(token);

		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}

		/**
		 * 获取贴牌对应的key
		 */
		LOG.info("keyPlan=========================================================================" + keyPlan);
		RestTemplate restTemplates = new RestTemplate();
		URI uris = util.getServiceUrl("user", "error url request!");
		String urls = uris.toString() + "/v1.0/user/brand/query/jh/key?brand_id=" + brandid + "&keyPlan=" + keyPlan;
		String results = restTemplates.getForObject(urls, String.class);
		JSONObject jsonObject1 = JSONObject.fromObject(results);
		JSONObject res = jsonObject1.getJSONObject("result");
		String jhKey = res.getString("jhKey");
		LOG.info("jhKey===============================" + jhKey);
		//调用聚合
		RealNameAuth realNameAuth1 = realnameAuthBusiness.realNameAuth(realname, idcard, userId,keyPlan);
		if (realNameAuth1.getResult() != null && "1".equals(realNameAuth1.getResult())) {
/*
            MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
            RestTemplate restTemplate = new RestTemplate();
            URI url = util.getServiceUrl("user", "error url request!");
            String uri = url.toString() + "/v1.0/users/updatestatus/status";
            requestEntity.add("brandId", sbrandId);
            requestEntity.add("phone", phone);
            requestEntity.add("status", "1");
            String result = restTemplate.postForObject(uri, requestEntity, String.class);*/
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "实名信息返回正确");
		} else {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "实名信息返回错误");
		}
		return map;

	}
	/**
	 * 实名验证（前端调用）
	 **/
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/realname/auth/{token}")
	public @ResponseBody
	Object realnameAuth(HttpServletRequest request,
						@RequestParam(value = "realname") String realname,
						@RequestParam(value = "idcard") String idcard,
						@PathVariable("token") String token) {
		LOG.info("=====进入实名认证");
		Map<String, Object> map = new HashMap<>();
		long userId;
		try {
			userId = TokenUtil.getUserId(token);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}
		String birthDate;
		try {
			birthDate = idcard.substring(6, 10);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "您的身份证号有误,请重新输入!");
			return map;
		}
		int birthYear = Integer.valueOf(birthDate);
		int nowYear = Integer.valueOf(DateUtil.getDateStringConvert(new String(), new Date(), "yyyy"));
		if (nowYear - birthYear < 18 || nowYear - birthYear > 60) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "很抱歉,仅对年龄18岁~60岁用户进行实名认证!");
			return map;
		}

		realname = realname.trim();
		idcard = idcard.trim();
//		RealNameAuth realNameAuth=realnameAuthBusiness.findRealNamesByIdcard(idcard);
		RealNameAuth realNameAuth = realnameAuthBusiness.findRealNamesAuthByUserId(userId);


		if (realNameAuth != null && realNameAuth.getUserId() != userId) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "你的证件号已在其他账户认证");
			return map;
		}

		realNameAuth = realnameAuthBusiness.findRealNamesByall(userId, idcard, realname);
		if (realNameAuth != null) {
			map.put(CommonConstants.RESULT, realNameAuth);
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "接口返回成功");
			return map;
		}
		realNameAuth = realnameAuthBusiness.findRealNamesAuthByUsserId(userId);
		if (realNameAuth != null && realNameAuth.getAuthTime() != null) {
			long starttime = realNameAuth.getAuthTime().getTime();
			long endtime = System.currentTimeMillis();
			starttime = starttime + 60 * 10 * 1000;
			if (starttime > endtime) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "操作过于频繁，请10分钟后再试!");
				return map;
			}
		}

		/**
		 * 根据userId去取brandId
		 */
		long brandid;
		try {
			brandid = TokenUtil.getBrandid(token);

		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}
		/**
		 * 获取贴牌对应的key
		 */
		LOG.info("=====keyPlan:" + keyPlan + "=====brandid:" + brandid);
		RestTemplate restTemplates = new RestTemplate();
		URI uris = util.getServiceUrl("user", "error url request!");
		String urls = uris.toString() + "/v1.0/user/brand/query/jh/key?brand_id=" + brandid + "&keyPlan=" + keyPlan;
		String results = restTemplates.getForObject(urls, String.class);
		LOG.info("=====results" + results);
		JSONObject jsonObject1 = JSONObject.fromObject(results);
		JSONObject res = jsonObject1.getJSONObject("result");

		String jhKey = res.getString("jhKey");
		LOG.info("jhKey===============================" + jhKey);
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT, realnameAuthBusiness.realNameAuth(realname, idcard, userId, jhKey));
		map.put(CommonConstants.RESP_MESSAGE, "接口返回成功");

		return map;

	}

	/**
	 * 实名验证
	 * @param request
	 * @param phone		用户手机号码
	 * @param realname	用户名
	 * @param brandid	贴牌
	 * @param idcard	身份证号码
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/realname/auth/backstage")
	public @ResponseBody
	Object BackstagerealnameAuth(HttpServletRequest request,
								 @RequestParam(value = "phone") String phone,
								 @RequestParam(value = "realname") String realname,
								 @RequestParam(value = "brandid", required = false, defaultValue = "-1") String brandid,
								 @RequestParam(value = "idcard") String idcard) {

		Map map = new HashMap();
		long userId = 0l;
		/** 根据用户phone查询用户信息 */
		if (!StringUtils.isEmpty(phone)) {
			URI uri = util.getServiceUrl("user", "error url request!");
			String url = uri.toString() + "/v1.0/user/query/phone";

			MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("phone", phone);

			RestTemplate restTemplate = new RestTemplate();
			String result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("/v1.0/user/query/phone接口返回RESULT：" + result);

			JSONObject jsonObject = JSONObject.fromObject(result);
			JSONObject resulObj = jsonObject.getJSONObject("result");
			if (null == resulObj) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
				return map;
			}
			if (resulObj.containsKey("id")) {
				//do other things
				userId = resulObj.getLong("id");
			} else {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
				return map;
			}
			if (resulObj.containsKey("brandId")) {
				brandid = String.valueOf(resulObj.getLong("brandId"));
			}
		} else {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
			return map;
		}

		realname = realname.trim();
		idcard = idcard.trim();

//		RealNameAuth realNameAuth=realnameAuthBusiness.findRealNamesByIdcard(idcard);
		RealNameAuth realNameAuth = realnameAuthBusiness.findRealNamesAuthByUserId(userId);

		if (realNameAuth != null && realNameAuth.getUserId() != userId) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "你的证件号已在其他账户认证");
			return map;
		}

		realNameAuth = realnameAuthBusiness.findRealNamesByall(userId, idcard, realname);
		if (realNameAuth != null) {
			map.put(CommonConstants.RESULT, realNameAuth);
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "接口返回成功");
			return map;
		}
		realNameAuth = realnameAuthBusiness.findRealNamesAuthByUsserId(userId);
		if (realNameAuth != null && realNameAuth.getAuthTime() != null) {
			long starttime = realNameAuth.getAuthTime().getTime();
			long endtime = System.currentTimeMillis();
			starttime = starttime + 60 * 10 * 1000;
			if (starttime > endtime) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "服务器繁忙，请稍后再试!");
				return map;
			}
		}
		/**
		 * 获取贴牌对应的key
		 *
		 */
		RestTemplate restTemplates = new RestTemplate();
		URI uris = util.getServiceUrl("user", "error url request!");
		String urls = uris.toString() + "/v1.0/user/brand/query/jh/key?brand_id=" + brandid + "&keyPlan=" + keyPlan;
		String results = restTemplates.getForObject(urls, String.class);
		JSONObject jsonObject1 = JSONObject.fromObject(results);
		JSONObject res = jsonObject1.getJSONObject("result");
		String jhKey = res.getString("jhKey");
		LOG.info("jhKey===============================" + jhKey);
		map.put(CommonConstants.RESULT, realnameAuthBusiness.realNameAuth(realname, idcard, userId, jhKey));
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "接口返回成功");
		return map;


	}


	/**
	 * 根据身份证号查询
	 */
	@Deprecated
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/realname/idcard")
	public @ResponseBody
	Object realNameByIdcard(HttpServletRequest request,
							@RequestParam(value = "idcard") String idcard) {
//		return realnameAuthBusiness.findRealNamesByIdcard(idcard);
		return null;

	}


	/**
	 * 根据姓名查询
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/realname/name")
	public @ResponseBody
	Object realNameByName(HttpServletRequest request,
						  @RequestParam(value = "realname") String realname) {
		return realnameAuthBusiness.findRealNamesAuthByName(realname);

	}

	/**
	 * 根据后台连接用userId查询
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/realname/userid")
	public @ResponseBody
	Object realNameByUserId(HttpServletRequest request,
							@RequestParam(value = "userid") long userid) {
		Map map = new HashMap();
		map.put("realname", realnameAuthBusiness.findRealNamesAuthByUsserId(userid));
		return map;

	}

	/**
	 * 根据userId查询
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/realname/{token}")
	public @ResponseBody
	Object realNameBytoken(HttpServletRequest request,
						   @PathVariable("token") String token) {
		Map map = new HashMap();
		long userId;
		try {
			userId = TokenUtil.getUserId(token);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT, realnameAuthBusiness.findRealNamesAuthByUsserId(userId));
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		return map;

	}

	/**
	 * 查询所有的记录分页显示
	 */

	@RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/realname/all")
	public @ResponseBody
	Object allRealNameAuth(HttpServletRequest request,
						   @RequestParam(value = "page", defaultValue = "0", required = false) int page,
						   @RequestParam(value = "size", defaultValue = "20", required = false) int size,
						   @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
						   @RequestParam(value = "sort", defaultValue = "authTime", required = false) String sortProperty) {

		Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
		return realnameAuthBusiness.findAllRealnames(pageable);


	}

	//根据userid注销用户的实名信息
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/realname/delrealname")
	@ResponseBody
	public Object delRealnameByUserid(HttpServletRequest request,
									  @RequestParam(value = "userId") long userid) {
		Map map = new HashMap();
		try {
			realnameAuthBusiness.delRealnameByUserid(userid);
		} catch (Exception e) {
			LOG.info(e.getMessage());
		}
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		return map;
	}

	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/realname/findby/userids")
	public @ResponseBody
	Object getRealNameByUserIds(HttpServletRequest request,
								@RequestParam("userIds") String[] suserIds
	) {
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> realNameMap = new HashMap<>();
		long[] userIds = null;
		if (suserIds.length > 0) {
			userIds = new long[suserIds.length];
			for (int i = 0; i < suserIds.length; i++) {
				userIds[i] = Long.valueOf(suserIds[i]);
			}
		}
		List<RealNameAuth> models = realnameAuthBusiness.findRealNamesAuthByUserIds(userIds);
		if (models != null && models.size() != 0) {
			for (int i = 0; i < models.size(); i++) {
				realNameMap.put(models.get(i).getUserId() + "", models.get(i));
			}
		}
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "查询成功");
		map.put(CommonConstants.RESULT, realNameMap);
		return map;
	}

	//添加实名用户信息
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/realname/add/realname")
	public @ResponseBody
	Object addRealnameAuth(HttpServletRequest request,
						   @RequestParam(value = "userId") long userId,
						   @RequestParam(value = "realname") String realname,
						   @RequestParam(value = "idCard") String idcard,
						   @RequestParam(value = "result", defaultValue = "3", required = false) String result,
						   @RequestParam(value = "message") String message
	) {
		Map map = new HashMap();
		RealNameAuth realnameAuth = realnameAuthBusiness.findRealnameAuthById(userId);
		if (realnameAuth == null) {
			RealNameAuth realnameAuths = new RealNameAuth();
			realnameAuths.setAuthTime(new Date());
			realnameAuths.setIdcard(idcard);
			realnameAuths.setMessage(message);
			realnameAuths.setRealname(realname);
			realnameAuths.setResult(result);
			realnameAuths.setUserId(userId);
			realnameAuthBusiness.addRealnameAuth(realnameAuths);
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "添加成功");
		} else {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "实名信息已存在");
		}
		return map;
	}

	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/realname/update/realname")
	public @ResponseBody
	Object setRealnameResult(HttpServletRequest request,
							 @RequestParam(value = "userId") long userId,
							 @RequestParam(value = "result") String result) {
		Map map = new HashMap();
		RealNameAuth realnameAuth = realnameAuthBusiness.findRealnameAuthById(userId);
		if (realnameAuth != null) {
			realnameAuthBusiness.updateRealnameMsg(userId, result);
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "修改成功");
		} else {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "查询失败");
		}

		return map;
	}

}
